package com.uwo.house.controller;

import com.uwo.house.config.JWTAuthenticationToken;
import com.uwo.house.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yanhao on 2017/6/16.
 */
@Controller
public class LoginController {

    @Autowired
    IUserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public Object login(HttpServletRequest req, Model model){
        Subject subject = SecurityUtils.getSubject();
        JWTAuthenticationToken token = (JWTAuthenticationToken)subject.getPrincipal();
        String userId = token.getUser().getId();
        String roleId = userService.getRoleIdByUserId(userId);
        Map<String, Object> json = new HashMap<String, Object>();
        String name = userService.getNameByUserId(userId);
        json.put("name",name);
        json.put("roleId",roleId);
        json.put("token", token.getToken());
        json.put("expire_time", token.getExpireTime());
        return json;
    }

    @RequestMapping("/403")
    public String unauthorizedRole(){
        return "/403";
    }
}
